package com.nue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nue.pojo.UmsUser;
import com.nue.mapper.UmsUserMapper;
import com.nue.service.IRedisService;
import com.nue.service.IUmsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nue.util.CommonResult;
import com.nue.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.auth0.jwt.JWT;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wk
 * @since 2020-08-19
 */
@Service
public class UmsUserServiceImpl extends ServiceImpl<UmsUserMapper, UmsUser> implements IUmsUserService {
    @Resource
    BCryptPasswordEncoder encoder;

    @Resource
    IRedisService redisService;


    @Override
    public String token(UmsUser user) throws JsonProcessingException {
        QueryWrapper<UmsUser> wrapper = new QueryWrapper<>();
        //根据用户名查询 用户对象
        wrapper.eq("username",user.getUsername());
        UmsUser queryUser = this.getOne(wrapper);
        if(queryUser!=null){
            //如果用户名存在则验证密码
            //如果密码一致则认为登录成功
            if(encoder.matches(user.getPassword(),queryUser.getPassword())){
                //将用户信息生成token数据返回给前端

                LocalDateTime now = LocalDateTime.now();
                queryUser.setLastlogin(now);
                String token = JWTUtil.create(queryUser);

                //保存登录状态信息 --》 ssdb
                //umsuser-admin

                updateLastLogin(queryUser.getId(),now);

                //缓存用户登录信息
                write2SSDB(queryUser,now);

                return token;
            }
        }

        return null;
    }
    private void write2SSDB(UmsUser user,LocalDateTime now) throws JsonProcessingException {
        Map info = new HashMap<>();
        info.put("username",user.getUsername());
        info.put("password",user.getPassword());
        info.put("id",user.getId());
        info.put("deptId",user.getDeptId());
        info.put("lastlogin",now.toInstant(ZoneOffset.of("+8")).toEpochMilli());

        ObjectMapper objectMapper = new ObjectMapper();
        String key = JWTUtil.KEY +"-"+user.getUsername();
        String userJson = objectMapper.writeValueAsString(info);

        redisService.set(key,userJson,60 *30);
    }

    /**
     * 更新最后登录成功的时间
     * @param id
     * @param now
     */
    private void updateLastLogin(Integer id, LocalDateTime now) {
        UmsUser user = new UmsUser();
        user.setId(id);
        user.setLastlogin(now);
        updateById(user);
    }
    @Override
    public boolean logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getClaim("username").asString();
        //删除key
        String key = JWTUtil.KEY +"-"+username;

        //设置有效期为0
        redisService.expire(key,0);

        return true;
    }


    @Override
    public CommonResult list(UmsUser user) {
        QueryWrapper<UmsUser> qu=new QueryWrapper<>();
        if(!StringUtils.isBlank(user.getUsername())){
            qu.like("username",user.getUsername());
        }
        if(user.getRegistlevel()!=null){
            qu.eq("registlevel",user.getRegistlevel());
        }
        if(user.getDeptId()!=null){
            qu.eq("dept_id",user.getDeptId());
        }
        if(user.getIfpage()==1){
            IPage<UmsUser> page=new Page<>(user.getPageNo(),user.getPageSize());
            return CommonResult.success(page(page,qu));
        }
        else{
            return CommonResult.success(list(qu));
        }


    }

    @Override
    public CommonResult saveOne(UmsUser user) {
        QueryWrapper<UmsUser> qu=new QueryWrapper<>();
        qu.eq("username",user.getUsername());
        //System.out.println(p);
        UmsUser u=getOne(qu);
        if(u!=null){
            return CommonResult.failed("用户名已存在");
        }
        user.setActive(1);
        user.setPassword(encoder.encode(user.getPassword()));
        boolean b=save(user);
        System.out.println("此时的b"+b);
        if(b)
           return CommonResult.success("创建成功");
        else
            return CommonResult.failed();
    }

    @Override
    public CommonResult update(UmsUser user) {

        user.setPassword(encoder.encode(user.getPassword()));
        if(updateById(user)){
            return CommonResult.success("ok");
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult back(Integer id) {
        UmsUser user=new UmsUser();
        user.setId(id);
        user.setActive(1);
        boolean i=this.updateById(user);
        if(i){
            return CommonResult.success("恢复成功");
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult del(Integer id) {
        UmsUser user =new UmsUser();
        user.setId(id);
        user.setActive(0);
        boolean i=this.updateById(user);
        if(i)return CommonResult.success("删除成功");
        return CommonResult.failed();
    }
}
